package com.anabur.bean.table;

import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import org.primefaces.component.picklist.PickList;
import org.primefaces.model.DualListModel;

import com.anabur.persistent.Empresa;

@FacesConverter("empresaConverter")
public class EmpresaConverter implements Converter {
 
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        return getObjectFromUIPickListComponent(component,value);
    }
 
    public String getAsString(FacesContext context, UIComponent component, Object object) {
        String string;
        if(object == null){
            string="";
        }else{
            try{
                string = String.valueOf(((Empresa)object).getCodigo());
            }catch(ClassCastException cce){
                throw new ConverterException();
            }
        }
        return string;
    }
 
    @SuppressWarnings("unchecked")
    private Empresa getObjectFromUIPickListComponent(UIComponent component, String value) {
        final DualListModel<Empresa> dualList;
        try{
            dualList = (DualListModel<Empresa>) ((PickList)component).getValue();
            Empresa empresa = getObjectFromList(dualList.getSource(),value);
            if(empresa==null){
            	empresa = getObjectFromList(dualList.getTarget(),value);
            }
             
            return empresa;
        }catch(ClassCastException cce){
            throw new ConverterException();
        }catch(NumberFormatException nfe){
            throw new ConverterException();
        }
    }
 
    private Empresa getObjectFromList(final List<?> list, String identifier) {
        for(final Object object:list){
            final Empresa empresa = (Empresa) object;
            if(empresa.getCodigo().equals(identifier)){
                return empresa;
            }
        }
        return null;
    }
}